package com.xunyji.demo03.realm.usedemo;

import com.xunyji.demo03.realm.CustomRealm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authc.pam.FirstSuccessfulStrategy;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SubjectDAO;
import org.apache.shiro.subject.Subject;
import org.junit.Test;

/**
 * @author AltEnter
 * @create 2019-01-23 16:22
 * @desc 自定义Realm使用Demo
 **/
public class CustomRealmDemo {
    @Test
    public void test01() {
        CustomRealm customRealm = new CustomRealm();
        // shiro加密 start
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        //选择加密方式
        matcher.setHashAlgorithmName("md5");
        //加密次数
        matcher.setHashIterations(1);
        // 给自定义Realm设置加密规则
        customRealm.setCredentialsMatcher(matcher);
//        shiro加密 end

        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        FirstSuccessfulStrategy firstSuccessfulStrategy = new FirstSuccessfulStrategy();
        ModularRealmAuthenticator modularRealmAuthenticator = new ModularRealmAuthenticator();
        modularRealmAuthenticator.setAuthenticationStrategy(firstSuccessfulStrategy);

        defaultSecurityManager.setAuthenticator(modularRealmAuthenticator);
        defaultSecurityManager.setRealm(customRealm);

        SecurityUtils.setSecurityManager(defaultSecurityManager);
        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken("fury", "111111");

        subject.login(token);
        System.out.println(String.format("认证结果为：%s", subject.isAuthenticated()));

        System.out.println(String.format("是否有admin角色：%s", subject.hasRole("admin")));
        System.out.println(String.format("是否有user:create角色：%s", subject.isPermitted("user:create")));

        subject.logout();
        System.out.println(String.format("认证结果为：%s", subject.isAuthenticated()));
    }



}

